package org.linlinjava.litemall.mechanismadmin.web;

import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallCart;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.db.domain.LitemallProduct;
import org.linlinjava.litemall.db.service.LitemallCartService;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.linlinjava.litemall.db.service.LitemallProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 购物车模块
 *
 * @author zhy
 * @create 2018-11-12 10:17
 **/
@RestController
@RequestMapping("/mechanismadmin/cart")
public class MechanismCartController {
	@Autowired
	private LitemallCartService cartService;

	@Autowired
	private LitemallProductService litemallProductService;

	@Autowired
	private LitemallGoodsService litemallGoodsService;

 	@GetMapping("getCart")
	public Object getCart(Integer userId) {
		if (userId == null) {
			return ResponseUtil.ok();
		}
		List<LitemallCart> litemallCarts = cartService.queryByUid(userId);
	    List<LitemallProduct> products = null;
		List<Map> list = cartService.queryCartGoods(userId);

		if(litemallCarts.size()>0){
			Set<Integer> cateGorlyId = litemallCarts.stream().map(x->x.getProductId()).collect(Collectors.toSet());
			products = litemallProductService.queryByProductId(new ArrayList<>(cateGorlyId));
		}

		Map<String, Object> result = new HashMap<>(16);
        result.put("goods",list);
        result.put("num",products);
		result.put("cart", litemallCarts);
		return ResponseUtil.ok(result);
	}

	@GetMapping("deleteGoods")
	public Object deleteGoods(Integer id, Integer userId) {
		if (id == null) {
			return ResponseUtil.ok();
		}
		int num = cartService.deleteOne(id, userId);
		Map<String, Object> result = new HashMap<>(16);
		result.put("deleteFlag", num);
		return ResponseUtil.ok(result);
	}

	@GetMapping("queryNumber")
	public Object queryNumber(String productIds, String nums) {
		List<String> ids = java.util.Arrays.asList(productIds.substring(0, productIds.length() - 2).split("@@"));
		List<String> numbers = java.util.Arrays.asList(nums.substring(0, nums.length() - 2).split("@@"));
		Integer a = 0;
		for(int i = 0; i < ids.size(); i++) {
			LitemallProduct product = litemallProductService.findById(Integer.parseInt(ids.get(i)));
			if(product.getNumber() < Integer.parseInt(numbers.get(i))){
				a = 1;
			}
		}
		return ResponseUtil.ok(a);
	}
}
